<template>
  <div v-loading="loading" :class="{'mobile-detail-wrap':showMobilePage}" class="project-detail">
    <template v-if="projectPageAuth">
      <step :mode="2" :is-show-scroll="showMobilePage" :order-status="detailData.projectStatus || 0" :step-list="stepList" :node-approvers="detailData.nodeApprovers"/>
      <div class="project-info" >
        <projectInfo :detail-data="detailData" />
        <projectData v-if="hasRouteAuth('crm:project:incomeData')" :detail-data="detailData" style="margin: 22px 0 14px" />
        <DetailTabs v-model="activeId" :tabs="tabList" style="margin-top: 6px"/>
        <div v-if="tabList.length > 0" class="project-content">
          <!-- 收入列表 -->
          <projectOrder v-if="activeId === 1" ref="projectOrderRef" :project-id="projectId" :supplier-name="supplierName" :detail-data="detailData" @getDetail="getDetail" />
          <!-- 成本列表 -->
          <projectCost v-if="activeId === 2" ref="projectCostRef" :detail-data="detailData" :project-id="projectId" @getDetail="getDetail" @getOrderList="getOrderList" />
          <!-- 核销记录 -->
          <charge-report v-if="activeId === 3" ref="chargereport" :detail-data="detailData" @getDetail="getDetail" />
          <!-- 发票合同 -->
          <InvoiceAndContract v-if="activeId === 4" ref="invoiceAndContract" :detail-data="detailData" @getDetail="getDetail" />
          <!-- 附件 -->
          <projectFile v-if="activeId === 5" :detail-data="detailData" :project-id="projectId" @getDetail="getDetail" />
        </div>
        <div v-else class="project-empty-container">
          <img :src="emptyImg" alt="">
          <div class="empty-text">暂无数据</div>
        </div>
        <div v-if="hasRouteAuth('crm:project:log')">
          <Title :title="'操作记录'" style="margin-bottom: 16px;"/>
          <div v-if="operateLogs && operateLogs.length > 0">
            <log-time-line :logs="logList" :edit-api="editLogRemark" @success="editRemarkSuccess" />
            <div v-if="logsNum > 3" class="log-open-btn" @click="switchOpen"> {{ logOpen?'收起':'展开' }}全部记录<i :class="logOpen?'el-icon-arrow-up':'el-icon-arrow-down'"/></div>
          </div>
          <EmptyPlaceholder v-else no-border empty-text="暂无操作日志" style="margin: 28px 0" />
        </div>
      </div>
      <projectFootBtn :detail-data="detailData" :project-id="projectId" @getOperateReports="getOperateReports" @getDetail="getDetail" @freshData="freshData" @fetchDataChargeList="fetchDataChargeList" />
    </template>
    <div v-else class="empty-container-noauth">
      <img :src="emptyImg" alt="">
      <div class="empty-text">暂无权限</div>
    </div>
  </div>
</template>

<script>
import emptyImg from '@/assets/empty-data-icon.png';
import step from '@/components/CreateOrder/orderDetail/step';
import projectInfo from '@/components/ProjectComponent/projectInfo';
import ChargeReport from '@/components/ProjectComponent/chargeReport';
import projectData from '@/components/ProjectComponent/projectData';
import projectOrder from '@/components/ProjectComponent/projectOrder';
import projectCost from '@/components/ProjectComponent/projectCost';
import projectFootBtn from '@/components/ProjectComponent/projectFootBtn';
import InvoiceAndContract from '@/components/ProjectComponent/projectInvoiceAndContract';
import projectFile from '@/components/ProjectComponent/projectFile';
import LogTimeLine from '@/components/Common/logTimeLine';
import DetailTabs from '@/components/Common/baseComponent/DetailTabs';
import { getProjectDetail } from '@/api/projectDetail.js';
import EmptyPlaceholder from '@/components/Common/emptyPlaceholder';
import Title from '@/components/Title';
import { hasRouteAuth } from '@/utils/permission';
import { mapState } from 'vuex';
import { getOperateReports, editLogRemark } from '@/api/order';

export default {
  components: {
    step, Title, projectOrder, projectCost, ChargeReport, EmptyPlaceholder,
    projectInfo, projectData, DetailTabs, projectFootBtn, InvoiceAndContract, projectFile, LogTimeLine
  },
  data() {
    return {
      emptyImg,
      activeId: 1,
      projectId: '',
      detailData: {},
      loading: false,
      operateLogs: [],
      logsNum: 0,
      miniLogs: [],
      logOpen: false,
      projectPageAuth: true,
      supplierName: ''
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'showMobilePage': state => state.app.showMobilePage
    }),
    logList() {
      return (this.logOpen || this.logsNum <= 3) ? this.operateLogs : this.miniLogs;
    },
    stepList() {
      const hide = this.detailData && this.detailData.departmentName ? this.detailData.departmentName.indexOf('销售部') !== -1 : false;
      let result = null;
      if (hide) {
        result = [
          { name: '待提交', id: 0 }, { name: '待初审', id: 1 }, { name: '待复审', id: 2 },
          { name: '待封存', id: 4 }, { name: '已封存', id: 5 }
        ];
      } else {
        result = [
          { name: '待提交', id: 0 }, { name: '待初审', id: 1 }, { name: '待复审', id: 2 },
          { name: '待确认', id: 3 }, { name: '待封存', id: 4 }, { name: '已封存', id: 5 }
        ];
      }
      return result;
    },
    tabList() {
      const isAdmin = this.userInfo.userName === '管理员';
      const greenColor = '';
      const redColor = '#FF504F';
      let isLink = false;
      let isFile = false;
      let isWriteOff = false;
      if (this.detailData && this.detailData.contract && this.detailData.invoiceInfo && this.detailData.contract.length > 0 && this.detailData.invoiceInfo.length > 0) {
        isLink = true;
      }
      if (this.detailData && this.detailData.attachment && this.detailData.attachment.length > 0) {
        isFile = true;
      }
      if (this.detailData && this.detailData.writeOffStatus === 1) {
        isWriteOff = true;
      }
      const result = [];
      if (hasRouteAuth('crm:projectInfo:orderList') || isAdmin) {
        result.push({ name: '收入列表', id: 1 });
      }
      if (hasRouteAuth('crm:projectInfo:costList') || isAdmin) {
        result.push({ name: '成本列表', id: 2 });
      }
      if (hasRouteAuth('crm:projectInfo:verificateList') || isAdmin) {
        result.push({ name: '核销记录', id: 3, dotColor: isWriteOff ? greenColor : redColor });
      }
      if (hasRouteAuth('crm:projectInfo:contractInvoice') || isAdmin) {
        result.push({ name: '发票合同', id: 4, dotColor: isLink ? greenColor : redColor });
      }
      if (hasRouteAuth('crm:projectInfo:attachmentUploading') || isAdmin) {
        result.push({ name: '附件上传', id: 5, dotColor: isFile ? greenColor : redColor });
      }
      return result;
    }
  },
  created() {
    this.projectId = Number(this.$route.params.id) || '';
    this.getDetail();
    if (this.tabList.length > 0) this.activeId = this.tabList[0].id;
  },
  methods: {
    editLogRemark,
    hasRouteAuth,
    // 编辑操作日志成功的回调
    editRemarkSuccess() {
      this.getOperateReports();
    },
    // 判断当前用户是否有这个权限
    isProjectAuth(item) {
      const userInfo = this.userInfo;
      const departmentName = item.department ? item.department.map(i => i.name).join(',') : '';
      const cooperationName = item.cooperation ? item.cooperation.map(i => i.userName).join(',') : '';
      let isCreate = false; // 创建人或者项目总监或协作人
      let isMediaAdmin = false; // 媒体销售业务全向展示
      let isBrandAdmin = false; // 内容营销平台全向展示;
      if (hasRouteAuth('crm:project:read')) {
        isCreate = item.creatorId === userInfo.id || item.projectDirectorId === userInfo.id || cooperationName.indexOf(userInfo.userName) >= 0;
      }
      if (hasRouteAuth('crm:project:mediaAdmin')) {
        isMediaAdmin = departmentName.indexOf('销售部') >= 0;
      }
      if (hasRouteAuth('crm:project:brandAdmin')) {
        isBrandAdmin = departmentName.indexOf('内容营销平台') >= 0;
      }
      // isCreate:当有 项目订单管理-可读 权限时，创建人为当前用户 || 项目总监为当前用户 || 执行人商务侧中有当前用户名 || 执行人资源侧中有当前用户名
      // isMediaAdmin:当有 销售部全部展示 权限时，departmentName中有销售部
      // isBrandAdmin:当有 内容营销平台全部展示 权限时，departmentName中有内容营销平台
      // 项目订单-全部展示权限
      return isCreate || isMediaAdmin || isBrandAdmin || hasRouteAuth('crm:project:admin');
    },
    // 获取操作日志列表
    getOperateReports() {
      const data = {
        id: this.projectId,
        type: 1,
        notShowNoAuthTip: true
      };
      getOperateReports(data).then(res => {
        if (res.code === 200) {
          this.operateLogs = res.data;
          const totalLogs = res.data ? JSON.parse(JSON.stringify(res.data)) : [];
          let logsNum = 0;
          totalLogs.forEach(i => {
            logsNum += i.operations.length;
          });
          this.logsNum = logsNum;
          if (logsNum > 3) {
          // 获取折叠后的数据
            const miniLogItem = [];
            for (let i = 0; i < totalLogs.length; i++) {
              if (miniLogItem.length >= 3) break;
              for (let j = 0; j < totalLogs[i].operations.length; j++) {
                totalLogs[i].operations[j].operationTime = totalLogs[i].operationTime;
                miniLogItem.push(totalLogs[i].operations[j]);
                if (miniLogItem.length >= 3) break;
              }
            }
            const miniLogs = [];
            miniLogItem.forEach(i => {
              const a = miniLogs.find(j => j.operationTime === i.operationTime);
              if (a) {
                a.operations.push(i);
              } else {
                miniLogs.push({
                  operationTime: i.operationTime,
                  operations: [i]
                });
              }
            });
            this.miniLogs = miniLogs;
          }
        }
      });
    },
    switchOpen() {
      this.logOpen = !this.logOpen;
    },
    getDetail(muted) {
      if (!muted) this.loading = true;
      const params = { id: this.projectId };
      getProjectDetail(params).then(res => {
        // 权限由后端判断，前端不需要判断
        // this.projectPageAuth = this.isProjectAuth(res.data);
        this.loading = false;
        if (res.code === 200) {
          if (res.data.department && res.data.department.length) res.data.departmentName = res.data.department.map(i => i.name).join('，');
          if (res.data.businessCooperation && res.data.businessCooperation.length) res.data.businessCooperationName = res.data.businessCooperation.map(i => i.userName).join('，');
          this.detailData = res.data;
          this.getOperateReports();
          this.$nextTick(() => {
            if (this.$refs.invoiceAndContract) this.$refs.invoiceAndContract.setDefault(this.detailData);
          });
        }
      }).catch((e) => {
        if (e.code === 500) {
          this.projectPageAuth = false;
        }
        this.loading = false;
      });
    },
    fetchDataChargeList() {
      if (this.$refs.chargereport) this.$refs.chargereport.fetchData();
    },
    getOrderList(supplier) {
      this.supplierName = supplier;
      this.activeId = 1;
    },
    freshData() {
      if (this.$refs.projectCostRef) this.$refs.projectCostRef.fetchData();
    }
  }
};
</script>

<style lang="scss" scoped>
.project-detail {
  min-height: calc(100vh - 60px);
  margin: 16px;
  background-color: #fff;
  padding-bottom: 80px;
  .project-info {
    padding: 16px 24px 32px 24px;
  }
  &.mobile-detail-wrap {
    margin: 0;
    .project-info {
      padding: 16px 12px 32px 12px;
    }
  }
  .project-content {
    margin-top: 16px;
  }
  &::v-deep {
    .order-detail-step {
      margin: 0;
    }
    .list-tab {
      border-radius:12px;
      padding-left: 0 !important;
    }
  }
  .project-empty-container {
    text-align: center;
    position: relative;
    margin-top: 20px;
    img {
      width: 90px;
    }
    .empty-text {
      color: #999;
      max-width: 300px;
      font-size: 14px;
      margin: 0 auto;
    }
  }
}
.log-open-btn {
  display:flex;
  justify-content:center;
  color: #333333;
  font-size:14px;
  cursor: pointer;
  align-items: center;
  margin-top: 10px;
  i {
    margin-left: 8px;
  }
}
.empty-container-noauth {
  text-align: center;
  position: relative;
  margin-top: 20px;
  box-shadow:2px 4px 13px 0px rgba(221,225,234,1);
  border-radius:12px;
  background-color: #fff;
  padding: 100px 24px;
  img {
    width: 90px;
  }
  .empty-text {
    color: #999;
    max-width: 300px;
    font-size: 14px;
    margin: 0 auto;
  }
}
</style>
